<?php

namespace App\Http\Middleware;

use App\Trip\Code;
use App\Trip\Traits\Response;
use Carbon\Carbon;
use Closure;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class UserToken
{
    use Response;

    /**
     * Handle an incoming request.
     *
     * @param Request                                                        $request
     * @param Closure(Request): (\Illuminate\Http\Response|RedirectResponse) $next
     *
     * @return \Illuminate\Http\Response|RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if (!auth()->getToken()) {
            return $this->error(Code::UNAUTHORIZED, 'token is required');
        }

        $response = $next($request);
        if (auth()->check()) {
            $time = auth()->payload()['exp'];
            $now  = Carbon::now()->timestamp;
            if (($time - $now) < config('trip.ttl.day') * 3 && ($time - $now) > 0) {
                $token      = auth()->refresh();
                $expired_at = Carbon::now()->addMinutes(config('jwt.ttl'))->timestamp;
                return $response->withHeaders([
                    'Authorization' => 'Bearer '.$token,
                    'ExpiredAt'     => $expired_at,
                ]);
            }
        } else {
            Log::error("token expired : ".auth()->getToken());
            return $this->error(Code::UNAUTHORIZED, 'token is expired');
        }

        return $response;
    }
}
